% Server of the game, awaits for a connection to be made and starts a game.
% for SWI-Prolog

:- include('main.pl').
:-use_module(library(socket)).

port(60003).
max_clients(5).

server:-
        port(Port),
        max_clients(Max_Clients),
        write('Server initiating at port: '), write(Port), nl,
        tcp_socket(Socket),
        tcp_bind(Socket, Port),
        tcp_listen(Socket, Max_Clients),
        tcp_open_socket(Socket, InputStream, _),
        dispatch(InputStream).
        %write('Client '), write(Client), write(' has connected'), nl,
        %server_loop(Stream, Client),
        %socket_server_close(Socket),
        %write('Server Exit'),nl.
        
% Create a new thread for each client
dispatch(Stream) :-
        tcp_accept(Stream, Socket, Client),
        write('Client '), write(Client), write(' has connected.'), nl,
        thread_create(process_client(Socket, Client), _,
                      [ detached(true)
                      ]),
        dispatch(Stream).

% setup_call_cleanup: executes tcp_open_socket and on success , handle_service.
% when handle_service is finished, executes close_connection.
process_client(Socket, Peer) :-
tcp_open_socket(Socket, In, Out),
       server_init(Socket, In, Out, Peer),
       close_connection(In, Out).

close_connection(In, Out) :-
        close(In, [force(true)]),
        close(Out, [force(true)]).

server_init(Socket, In, Out, Peer):-
                    write('Server init.'),
                    write(Out, 'Welcome').
                    %read(In, Input),
                    %write('Received: '), write(Input), nl,
                    %server_init(Socket, In, _, Peer).
                    %close(IN), close(Out).
% se in == hello,
 % server loop
 
% server loop,
  % read stream while stream != bye,
    % process game.


%server_loop(In, Out, Peer):-
%        tcp_accept(AcceptFd,Socket2,_),
%        tcp_open_socket(Socket2,In,Out),
%        write(Out,Txt),
%        close(In),
%        close(Out),
%        server_loop(AcceptFd,Txt).